<?php
namespace app\admin\controller;
use app\common\controller\Backend;
use think\Controller;
use think\Request;
use fast\Tree;
use fast\Cols;
use fast\Random;
//列
class Column extends Backend
{
    //Column模型对象
    protected $model = null;
    protected $modeldata = array();
    public function _initialize(){
        parent::_initialize();
        $this->model = model('Column');
        $this->modeldata = model('Module')->select();
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function add(){
        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            if ($params){
                $this->modelValidate = false;
                if ($this->dataLimit){
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try{
                    //是否采用模型验证
                    if ($this->modelValidate){
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $params['itemid'] = str_replace('-','',Random::uuid());
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false){
                        $this->success();
                    }else{
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e){
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            $moduleid = $this->request->get("moduleid");
            $this->view->assign("moduleid",$moduleid?$moduleid:0);
            if($moduleid){
                $m = model('Module')->get($moduleid);
                $cname = $m['enname'];
            }else{
                $cname = '';
            }
            $this->view->assign("cname",$cname);
            return $this->view->fetch();
        }
    }
    public function index(){
        $columnlist = Cols::columnread('column');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('pkey_name')){
            return $this->selectpage();
        }
        $searchfileds = array();
        $searchfileds['columnname'] = 'varcharmid';
        $searchfileds['columnenname'] = 'varcharmid';
        $searchfileds['moduleid'] = 'bigint';
        list($where, $sort, $order, $offset, $limit) = $this->buildparams($searchfileds);
        $limit = 200;
        $order = 'desc';
        $sort = 'listorder';
        $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
        $totalpage = 0;$page = 1;
        if($limit>0){
            //总页数
            $totalpage = $total%$limit==0?intval($total/$limit):intval($total/$limit)+1;
            //当前页
            if($offset>0){
                $page = intval($offset/$limit)+1;
            }
        }
        $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
        for ($i = 0; $i < count($list); $i++) {
            $list[$i]['isshowlist'] = ($list[$i]['isshowlist']?'是':'否');
            $list[$i]['isshowadd'] = ($list[$i]['isshowadd']?'是':'否');
            $list[$i]['isshowedit'] = ($list[$i]['isshowedit']?'是':'否');
            $list[$i]['isoption'] = ($list[$i]['isoption']?'是':'否');
            switch ($list[$i]['relate']) {
                  case 1:
                    $list[$i]['relate'] = '一对一';
                  break;
                  case 2:
                    $list[$i]['relate'] = '多对一';
                  break;
                  case 3:
                    $list[$i]['relate'] = '多对多';
                  break;
                  case 4:
                    $list[$i]['relate'] = '一对多';
                  break;
                  default:
                    $list[$i]['relate'] = '';
                  break;
            }
            $columntype = $list[$i]['columntype'];
            switch ($columntype) {
              case 'varcharlong':
                $list[$i]['columntype'] = 'varchar(1000)';
              break;
              case 'varcharmid':
                $list[$i]['columntype'] = 'varchar(400)';
              break;
              case 'varcharshort':
                $list[$i]['columntype'] = 'Varchar(100)';
              break;
              case 'identity':
                $list[$i]['columntype'] = '自动增长';
              break;
              case 'guid':
                $list[$i]['columntype'] = 'guid';
              break;
              case 'int':
                $list[$i]['columntype'] = 'int(10)';
              break;
              case 'bigint':
                $list[$i]['columntype'] = 'bigint(20)';
              break;
              case 'smallint':
                $list[$i]['columntype'] = 'smallint(4)';
              break;
              case 'bool':
                $list[$i]['columntype'] = 'tinyint(1)';
              break;
              case 'float':
                $list[$i]['columntype'] = 'float(4,2)';
              break;
              case 'decimal':
                $list[$i]['columntype'] = 'decimal(4,2)';
              break;
              case 'double':
                $list[$i]['columntype'] = 'double(18,2)';
              break;
              case 'image':
                $list[$i]['columntype'] = 'image';
              break;
              case 'file':
                $list[$i]['columntype'] = 'file';
              break;
              case 'text':
                $list[$i]['columntype'] = 'text';
              break;
              case 'enum':
                $list[$i]['columntype'] = 'enum';
              break;
              default:
                # code...
                break;
            }

            switch ($list[$i]['columncheck']) {
              case 'required':
                $list[$i]['columncheck'] = '必须填写';
              break;
              case 'length(8~16)':
                $list[$i]['columncheck'] = '长度在8—16之间';
              break;
              case 'digits':
                $list[$i]['columncheck'] = '数字';
              break;
              case 'letters':
                $list[$i]['columncheck'] = '字母';
              break;
              case 'date':
                $list[$i]['columncheck'] = '日期格式yyyy-mm-dd';
              break;
              case 'email':
                $list[$i]['columncheck'] = 'Email';
              break;
              case 'time':
                $list[$i]['columncheck'] = '时间';
              break;
              case 'url':
                $list[$i]['columncheck'] = '网址';
              break;
              case 'qq':
                $list[$i]['columncheck'] = 'QQ';
              break;
              case 'IDcard':
                $list[$i]['columncheck'] = '身份证号';
              break;
              case 'tel':
                $list[$i]['columncheck'] = '电话号码';
              break;
              case 'mobile':
                $list[$i]['columncheck'] = '手机号';
              break;
              case 'zipcode':
                $list[$i]['columncheck'] = '邮编';
              break;
              case 'chinese':
                $list[$i]['columncheck'] = '中文';
              break;
              case 'username':
                $list[$i]['columncheck'] = '用户名3-12位数字、字母、下划线';
              break;
              case 'password':
                $list[$i]['columncheck'] = '密码6-16位字符，不能包含空格';
              break;
              case 'integer':
                $list[$i]['columncheck'] = '整数';
              break;
              case 'integer(+)':
                $list[$i]['columncheck'] = '正整数';
              break;
              case 'integer(-)':
                $list[$i]['columncheck'] = '负整数';
              break;
              default:
                $list[$i]['columncheck'] = '';
                break;
            }
        }
        $result = array("total" => $total, "rows" => $list);
        //$moduledata = model('Module')->where(array())->select();
        $this->view->assign("lists",$result['rows']);
        // $this->view->assign("moduledata", $this->moduledata);
        // $this->view->assign("provincedata", $this->provincedata);
        // $this->view->assign("columns",$this->columnarry);
        $this->view->assign("columnlist",$columnlist);
        $this->view->assign("total",$result['total']);
        $this->view->assign("offset",$offset);
        $this->view->assign("limit",$limit);
        $this->view->assign("totalpage",$totalpage);
        $this->view->assign("page",$page);
        return $this->view->fetch();
    }
    //生成列缓存
    public function makefile(){
        if($this->request->get('name')){
            $ll = $this->model->getColumnsByModel($this->request->get('name'));
            $lls = array();
            foreach ($ll as $k => $v) {
                $lls[ucfirst($v['columnenname'])] = $v;
            }
            $string = "<?php return ".var_export($lls, true)."; ?>";
            $filename = COLUMN_PATH.DS.$this->request->get('name').'.php';
            //echo $filename;exit;
            $result = file_put_contents($filename, $string);
            if(@$fp = fopen($filename, 'wb')) {
                flock($fp, LOCK_EX);
                $len = fwrite($fp, $string);
                flock($fp, LOCK_UN);
                fclose($fp);
                //if(DT_CHMOD) @chmod($filename, DT_CHMOD);
                echo $len;exit;
            } else {
                echo '失败了';exit;
            }
        }
    }
}
